<?php
namespace app\api\controller;
use think\Db;
use think\Controller;
use think\Request;

class Login extends controller
{
    public function index()
    {
        $code = input("post.code");
        $appid = 'wx6b0bc166ece6d3ea';
        $secret = '546d302beeb5904785c4d6e69a656177';
        $data = "?js_code=" . $code . "&appid=" . $appid . "&secret=" . $secret;
        $url = 'https://api.weixin.qq.com/sns/jscode2session' . $data;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
       
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $wxData = curl_exec($ch);
        $wxData = json_decode($wxData);
        //echo json_encode($wxData);
        // halt($wxData);
        @$openId = $wxData->openid;
        @$sessionId = $wxData->session_key;
        if (!$openId) {
            echo json_encode(array('status'=>0,'err'=>'获取登陆信息失败'));
            exit();
        }

        $user = Db::table('yup_user')->where('openid',$openId)->find();
        if($user){
           //说明存在该用户
            $userId = $user['id'];
        }else{
          
          $userData = ['openid'=>$openId,'create_time'=>date('Y-m-d H:i:s')];
          $userId = Db::table('yup_user')->insertGetId($userData);
        }

        $userinfo = Db::table('yup_user')->where('id',$userId)->find();

        
        $result['userId'] = $userId;
        $result['sessionId'] = $sessionId;
        echo json_encode(array('status'=>1,'data'=>$result));
    }




}